import { useEffect, useRef } from "openinula";
import * as echarts from "echarts";
import { registerResize } from "./utils";

function InulaEcharts(props) {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const disposeResize = useRef(null);

  const { style, option, optionOpts, loadingOpts, initTheme, initOpts, onInit, onInited, autoResize, ...eProps } = props;

  useEffect(() => {
    // create
    if (onInit) {
      onInit(echarts);
    }

    chartInstance.current = echarts.init(chartRef.current, initTheme, initOpts);

    if (onInited) {
      onInited(chartInstance.current, echarts);
    }

    return () => {
      // dispose
      if (disposeResize.current) {
        disposeResize.current();
        disposeResize.current = null;
      }

      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (!chartInstance.current) {
      return;
    }

    // update
    chartInstance.current.showLoading(
      Object.assign(
        {
          text: "",
          maskColor: "rgba(255,255,255,0)",
        },
        loadingOpts
      )
    );

    if (option) {
      chartInstance.current.setOption(option, optionOpts);
      chartInstance.current.hideLoading();
    } else {
      chartInstance.current.clear();
    }
  }, [props.option]);

  useEffect(() => {
    if (!chartInstance.current) {
      return;
    }

    if (autoResize && !disposeResize.current) {
      disposeResize.current = registerResize(chartRef.current, () => {
        if (chartInstance.current) {
          chartInstance.current.resize();
        }
      });
    } else if (!autoResize && disposeResize.current) {
      disposeResize.current();
      disposeResize.current = null;
    }
  }, [props.autoResize]);

  const chartStyle = Object.assign(
    {
      width: "100%",
      height: "100%",
    },
    style
  );

  return <div {...eProps} ref={chartRef} style={chartStyle}></div>;
}

export default InulaEcharts;
